"""
S4 Custom Prompts Split Node  
Author: S4MUEL
GitHub: https://github.com/S4MUEL-404/ComfyUI-S4API

Split text based on various delimiters into multiple outputs.
"""

from ..s4_logger import S4APILogger, log_processing_step


class S4PromptsSplit:
    """
    Split text into exactly 4 parts based on configurable delimiter.
    """

    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "text": (
                    "STRING", 
                    {
                        "default": "", 
                        "multiline": True,
                        "tooltip": "Text to split into multiple parts"
                    }
                ),
                "delimiter": (
                    ["Comma", "Semicolon", "Space", "Newline", "Forward Slash", "Custom"], 
                    {
                        "default": "Comma",
                        "tooltip": "Delimiter to use for splitting text"
                    }
                ),
            },
            "optional": {
                "custom_delimiter": (
                    "STRING",
                    {
                        "default": "|",
                        "multiline": False,
                        "tooltip": "Custom delimiter string (used when delimiter is 'Custom')"
                    }
                ),
                "trim_parts": (
                    "BOOLEAN",
                    {
                        "default": True,
                        "tooltip": "Remove whitespace from each split part"
                    }
                ),
            }
        }

    RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING")
    RETURN_NAMES = ("text1", "text2", "text3", "text4")
    FUNCTION = "split_text"
    CATEGORY = "💀PromptsO"
    DESCRIPTION = "Split text based on delimiter and output up to 4 parts."

    def get_delimiter_char(self, delimiter: str, custom_delimiter: str = "|") -> str:
        """Map delimiter name to actual character"""
        delimiter_map = {
            "Comma": ",",
            "Semicolon": ";",
            "Space": " ",
            "Newline": "\\n",
            "Forward Slash": "/",
            "Custom": custom_delimiter
        }
        return delimiter_map.get(delimiter, ",")

    def split_text(self, text, delimiter="Comma", custom_delimiter="|", trim_parts=True):
        """Split text based on delimiter and return up to 4 parts"""
        
        log_processing_step("PromptsSplit", "Starting text splitting")
        
        if not text or not text.strip():
            S4APILogger.warning("PromptsSplit", "Empty text input received")
            return ("", "", "", "")
        
        # Get actual delimiter character
        actual_delimiter = self.get_delimiter_char(delimiter, custom_delimiter)
        
        S4APILogger.debug("PromptsSplit", f"Using delimiter: '{actual_delimiter}' ({delimiter})")
        preview = text[:50] + "..." if len(text) > 50 else text
        S4APILogger.debug("PromptsSplit", f"Input text: {preview}")
        
        # Split the text
        parts = text.split(actual_delimiter)
        original_parts_count = len(parts)
        
        # Apply trimming if requested
        if trim_parts:
            parts = [part.strip() for part in parts]
            S4APILogger.debug("PromptsSplit", "Applied whitespace trimming to parts")
        
        # Filter out empty parts if trimming was applied
        if trim_parts:
            non_empty_parts = [part for part in parts if part]
            if len(non_empty_parts) != len(parts):
                S4APILogger.debug("PromptsSplit", f"Removed empty parts: {len(parts)} → {len(non_empty_parts)} parts")
                parts = non_empty_parts
        
        # Ensure we have exactly 4 outputs (pad with empty strings)
        while len(parts) < 4:
            parts.append("")
        
        # Log results
        valid_parts_count = len([p for p in parts[:4] if p])
        result_info = f"Split into {valid_parts_count}/4 parts"
        
        for i, part in enumerate(parts[:4]):
            if part:
                preview = part[:30] + "..." if len(part) > 30 else part
                result_info += f", Part{i+1}: {preview} ({len(part)} chars)"
        
        S4APILogger.success("PromptsSplit", f"Text splitting completed - {result_info}")
        
        # Return only the first 4 parts
        return tuple(parts[:4])

    @classmethod
    def IS_CHANGED(cls, **kwargs):
        return float("NaN")